<?php

namespace App\Task;

use App\Model\Applet;
use App\Model\AppletPlayletRel;
use App\Model\Playlet;
use App\Model\PlayletEpisodes;
use GuzzleHttp\Client;
use Hyperf\Crontab\Annotation\Crontab;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Utils\ApplicationContext;
use Psr\Log\LoggerInterface;

class DyUpDramaTask
{
    protected LoggerInterface $logger;

    public static $getTokenUrl = "https://open.douyin.com/oauth/client_token/";


    public static $getDramaUrl = "https://open.douyin.com/api/playlet/v2/album/fetch/";

    public function __construct(protected LoggerFactory $loggerFactory)
    {
        $this->logger = $this->loggerFactory->get('log', 'dyUpDrama');
    }

    public function execute()
    {
//        return;
        $this->logger->info(date('Y-m-d H:i:s') . '------------------------开始定时获取剧目提审数据');
        $this->logger->info('获取短剧中提审的的数据');
        //获取需要获取任务的视频
        $playletData = Playlet::query()->where('album_id','!=',0)->where('album_status',3)->get();
        if($playletData->isNotEmpty()){

            //查询抖音小程序的ID 获取appID 和密钥
            $this->logger->info('查询抖音小程序的ID 获取appID 和密钥');
            $appletInfo = Applet::query()->where(['type' => 2,'id' => 20000])->select(['id','name','app_id','app_secret'])->first();
            if(!empty($appletInfo)) {

                foreach ($playletData as $playletDatum) {
                    //短剧名称
                    $playlet_name = $playletDatum->name;

                    $applet_name = $appletInfo->name;
                    $this->logger->info('获取绑定此短剧的抖音小程序token:'.$applet_name);
                    $accessToken = $this->getDyAccessToken($appletInfo->id,$appletInfo->app_id,$appletInfo->app_secret);
                    $this->logger->info('获取短剧审核数据:'.$playlet_name);
                    $dramaInfo = $this->getDramaInfo($playletDatum->album_id,$appletInfo->app_id,$accessToken);
                    if(!empty($dramaInfo) && !empty($dramaInfo['album_info_list'])){
                        $album_info_list = $dramaInfo['album_info_list'];
                        $albumData = array();
                        foreach ($album_info_list as $album_info){
                            if($album_info['album_audit_info']['version'] == $playletDatum->album_version){
                                $albumData = $album_info;
                                break;
                            }
                        }
                        if(!empty($albumData)){
                            $this->logger->info('短剧名称为:'.$playlet_name);
                            //状态 1-未提交 2-已提交 3-已审出
                            if($albumData['album_audit_info']['status'] == 3){
                                //审核状态 99-未审核 98-审核中 1-不可播放 2-可播放
                                if($albumData['album_audit_info']['audit_status'] == 2) {
                                    $playletDatum->scope_list = implode(',',$albumData['album_audit_info']['scope_list']);
                                    if(!empty($albumData['album_audit_info']['audit_msg'])){
                                        $playletDatum->album_msg = $albumData['album_audit_info']['audit_msg'];
                                    }
                                    $playletDatum->save();
                                }
                            }
                        }
                    }
                }
            }else{
                $this->logger->error('查询抖音小程序ID：没有对应的抖音小程序数据');
            }
        }else{
            $this->logger->info('没有短剧审核数据');
        }
        $this->logger->info(date('Y-m-d H:i:s') . '------------------------结束定时获取剧目提审数据');
    }
    public function getDyAccessToken($applet_id,$app_id,$app_secret){

        $container = ApplicationContext::getContainer();

        $redis = $container->get(\Hyperf\Redis\RedisFactory::class)->get('dy');

        $key = 'dy_admin_access_token';
        $key .= $applet_id;
        $accessToken = $redis->get($key);
        if(empty($accessToken)){
            $params         = [
                'grant_type' => 'client_credential',
                'client_key'    => $app_id,
                'client_secret'   => $app_secret
            ];
            //获取token
            $accessTokenInfo     = $this->request($params, self::$getTokenUrl,'POST');
            if (!empty($accessTokenInfo['data']['access_token'])){
                $accessToken = $accessTokenInfo['data']['access_token'];
                $redis->setex($key,7100,$accessToken);
            }else{
                $accessToken = "";
            }
        }
        $this->logger->info('抖音token为：'.$accessToken);
        return $accessToken;
    }

    public function getDramaInfo($album_id,$app_id,$accessToken){

        $params         = [
            "ma_app_id"   =>$app_id,
            "query_type"   => 2,
            "single_query"    => [
                'album_id' => $album_id,
                "offset" => 0,
                "limit" => 20
            ]
        ];
        $taskUrl = self::$getDramaUrl;
        $this->logger->info('请求剧目信息数据：'.PHP_EOL.var_export(['result' => $params], true));
        $this->logger->info('请求剧目信息Url：'.$taskUrl);
        $postResult  = $this->request($params, $taskUrl,'POST',$accessToken);
        if($postResult['err_no'] == 0){
            $this->logger->info('调用剧目信息接口成功 返回数据：'.PHP_EOL.var_export(['result' => $postResult], true));
            return $postResult['data']['single_data'];
        }else{
            $this->logger->error('调用剧目信息接口失败 返回数据：'.PHP_EOL.var_export(['result' => $postResult], true));
        }
        return false;
    }
    /**
     * 传入数组进行HTTP POST请求
     */
    function request(array $params, string $url,string $method,string $access_token = null)
    {
        $client   = new Client([
            'timeout' => 3
        ]);
        $headers       = ['Content-Type' => 'application/json'];
        if(!empty($access_token)){
            $headers['access-token'] = $access_token;
        }

        $requestParams = [
            'headers' => $headers,
        ];
        if ($method == 'GET') {
            $requestParams['query'] = $params;
        } else {
            $requestParams['json'] = $params;//json_encode($params,JSON_UNESCAPED_UNICODE);
        }
        $response = $client->request($method,$url, $requestParams);
        if ($response->getStatusCode() !== 200) {
            return '';
        }
        $result   = $response->getBody()->getContents();
        $resultArr = json_decode($result,true);
        return $resultArr;

    }
}